﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace MVCPets.Helpers
{
  public static class ImageHelper
  {
    public static byte[] ResizeImage(Stream OriginalFile, int NewWidth, int MaxHeight, string fileExt)
    {
      using(Image original = Image.FromStream(OriginalFile))
      {
        if(original.Width <= NewWidth)
          NewWidth = original.Width;

        int NewHeight = original.Height * NewWidth / original.Width;

        if(NewHeight > MaxHeight)
        {
          NewWidth = original.Width * MaxHeight / original.Height;
          NewHeight = MaxHeight;
        }

        using(Bitmap bmPhoto = (Bitmap)System.Drawing.Image.FromStream(OriginalFile))
        {

          Bitmap tmp = new Bitmap(bmPhoto.Width, bmPhoto.Height);

          using(Graphics grPhoto = Graphics.FromImage(tmp))
          {
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
            grPhoto.DrawImage(bmPhoto, new Rectangle(0, 0, NewWidth, NewHeight), 0, 0, NewWidth, NewHeight, GraphicsUnit.Pixel);

            using(MemoryStream mm = new MemoryStream())
            {
              switch(fileExt.ToLower())
              {
                case ".png":
                  bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Png);
                  break;
                case ".gif":
                  bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Gif);
                  break;
                case ".jpg":
                  bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
                  break;
                default:
                  bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
                  break;
              }

              byte[] toReturn = mm.GetBuffer();
              return toReturn;
            }
          }
        }
      }
    }
  }
}
